package com.dongdongshop.service.impl;

import com.dongdongshop.mapper.TbGoodsDescMapper;
import com.dongdongshop.mapper.TbGoodsMapper;
import com.dongdongshop.mapper.TbItemMapper;
import com.dongdongshop.page.PageResult;
import com.dongdongshop.pojo.*;
import com.dongdongshop.service.TbGoodsService;
import com.dongdongshop.vo.GoodsVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

@Service
@DubboService
public class TbGoodsServiceImpl implements TbGoodsService {

    @Autowired
    private TbGoodsDescMapper tbGoodsDescMapper;

    @Autowired
    private TbGoodsMapper goodsMapper;
    @Autowired
    private TbItemMapper itemMapper;
    @Override
    @Transactional
    public void addGoodsAndGoodsDesc(TbGoods good, TbGoodsDesc tgd, List<TbItem> items) {
        goodsMapper.insertSelective(good);
        tgd.setGoodsId(good.getId());
        tbGoodsDescMapper.insertSelective(tgd);
        for (TbItem item : items) {
            item.setGoodsId(good.getId());
            itemMapper.insertSelective(item);
        }
    }

    @Override
    public PageResult<GoodsVo> listGoods(Integer pageNum, Integer pageSize, String name) {
        PageHelper.startPage(pageNum,pageSize);
        List<GoodsVo> listVo =  goodsMapper.selectByCategory(name);
        PageInfo<GoodsVo> in = new PageInfo<>(listVo);
        return new PageResult(in.getPageNum(),in.getPageSize(),in.getTotal(),in.getPages(),in.getList());
    }

    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Override
    public void updateAudit(Long[] ids) {
        TbGoodsExample example = new TbGoodsExample();
        TbGoodsExample.Criteria criteria = example.createCriteria();
        criteria.andIdIn(Arrays.asList(ids));
        List<TbGoods> tbGoods = goodsMapper.selectByExample(example);
        for (TbGoods good : tbGoods) {
            good.setAuditStatus("1");
            goodsMapper.updateByPrimaryKeySelective(good);
        }
        rocketMQTemplate.convertAndSend("2204dk-topic",ids);
    }

    @Override
    public void updateAuditNo(Long[] ids) {
        TbGoodsExample example = new TbGoodsExample();
        TbGoodsExample.Criteria criteria = example.createCriteria();
        criteria.andIdIn(Arrays.asList(ids));
        List<TbGoods> tbGoods = goodsMapper.selectByExample(example);
        for (TbGoods good : tbGoods) {
            good.setAuditStatus("2");
            goodsMapper.updateByPrimaryKeySelective(good);
        }
    }

    @Override
    public TbGoods selectGoodsById(Long id) {
        return goodsMapper.selectByPrimaryKey(id);
    }
}
